#!/usr/bin/python2

import sys

import pygame

from utils import Constants


class Player(pygame.sprite.Sprite):

    def __init__(self, x, y):
        # Initialize parent
        pygame.sprite.Sprite.__init__(self)
        # Create singleton group for sprite and add sprite to group
        self.__group = pygame.sprite.GroupSingle()
        self.add(self.__group)
        # Set the image and bounds
        self.image = pygame.surface.Surface((Constants.PLAYER_SIZE, ) * 2)
        self.image.fill(pygame.color.Color(Constants.PLAYER_COLOR))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.__rotation = 0
        self.dead = False

    def draw(self, surface):
        self.__group.draw(surface)

    def fall(self, delta, groups):
        x = self.rect.x
        y = self.rect.y
        speed = Constants.PLAYER_FALL_SPEED
        s = pygame.sprite.spritecollideany(self, groups["speed"])
        if s:
            speed *= s.multiplier()
        if self.__rotation == 0:
            self.rect.y += speed * delta
        elif self.__rotation == 90:
            self.rect.x -= speed * delta
        elif self.__rotation == 180:
            self.rect.y -= speed * delta
        elif self.__rotation == 270:
            self.rect.x += speed * delta
        if pygame.sprite.spritecollideany(self, groups["walls"]) \
                or pygame.sprite.spritecollideany(self, groups["doors"]):
            self.rect.x = x
            self.rect.y = y
        elif pygame.sprite.spritecollideany(self, groups["spikes"]):
            self.dead = True
        else:
            f = pygame.sprite.spritecollideany(self, groups["finish"])
            if f:
                f.kill()
            else:
                k = pygame.sprite.spritecollideany(self, groups["keys"])
                if k:
                    k.unlock(groups)

    def group(self):
        return self.__group

    def keydown(self, event):
        result = False
        return result

    def keyup(self, event):
        result = False
        return result

    def update(self, delta, rotation, groups):
        if rotation in (0, 90, 180, 270):
            self.__rotation = rotation
        self.fall(delta, groups)
